<?php
	function checksign($xml){
		$nodes =$xml->documentElement->childNodes;
		$set=array();
		foreach ($nodes as $elem ) {
			if($elem->nodeType==1){
				$set[$elem->nodeName]=$elem->nodeValue;
			}
		}
		if($set['sign']==sign($set)){
			return true;
		}else{
			return false;
		}
	}

	$xml = file_get_contents('php://input');
	$xml_tree = new DOMDocument();
	$xml_tree->loadXML($xml);
	$paystate=1;
	
				//$db->insert('test',array('out_trade_no'=>$xml));
	if($xml_tree->getElementsByTagName('return_code')->item(0)->nodeValue=='SUCCESS'){
		if(checksign($xml_tree)){
			if($xml_tree->getElementsByTagName('result_code')->item(0)->nodeValue=='SUCCESS'){
				$out_trade_no	= $xml_tree->getElementsByTagName('out_trade_no')->item(0)->nodeValue;	    //获取订单号
				$total_fee		= $xml_tree->getElementsByTagName('total_fee')->item(0)->nodeValue/100;			//获取总价格
				try{
					$db->beginTransaction();
					$where=array('rechargeId'=>$out_trade_no,'state'=>0);
					$record=$db->get('member_recharge','*',$where);
					if($record){
						$user=$db->get('members','*',array('uid'=>$record['uid']));
						$set=array('rechargeAmount'=>$total_fee,'state'=>1,'info'=>'微信充值','actionUid'=>$record['uid'],'#rechargeTime'=>'UNIX_TIMESTAMP()','coin'=>$user['coin'],'fcoin'=>$user['fcoin']);
						if($db->update('member_recharge',$set,$where)){							
							$sql="call setCoin(".$total_fee.", ".$user['fcoin'].", ".$record['uid'].", 1, 0, '充值', ".$record['id'].", '".$out_trade_no."', '')";
							$db->query($sql);
						}
					}else{
						$paystate=6;
					}					
					$db->commit();
				}catch(Exception $e){
					$paystate=5;
				}
			}else{
				$paystate=4;
			}
		}else{
			$paystate=3;
		}
	}else{
		$paystate=2;
	}
	echo $paystate;
	if($paystate==1){
		echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
	}else{
		echo "<xml><return_code><![CDATA[FAIL]]></return_code></xml>";
	}
?>